package fnsvr

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// mysql连接
type MysqlConn struct {
	mysqlConn *gorm.DB
}

// 获取mysql连接
func (m *MysqlConn) Conn() *gorm.DB {
	return m.mysqlConn.Session(&gorm.Session{})
}

// 建立mysql连接
func CreateMysqlConn(cfg *MysqlConfig) (*MysqlConn, error) {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	return &MysqlConn{mysqlConn: db}, nil
}

type DbId interface {
	int | int8 | int16 | int32 | int64 |
		uint | uint8 | uint16 | uint32 | uint64 |
		string
}

// 判断数据库总是否存在指定id的数据
func DbExistsByID[T DbId](db *gorm.DB, model any, id T) (bool, error) {
	var count int64
	result := db.Model(model).Select("id").Where("id = ?", id).Count(&count)

	if result.Error != nil {
		return false, result.Error
	}
	return count > 0, nil
}
